import tkinter as tk
from tkinter import messagebox
import hashlib
import sqlite3
import datetime

# 连接数据库
conn = sqlite3.connect('hospital_assistant.db')
cursor = conn.cursor()

# 创建用户表
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT NOT NULL,
    password TEXT NOT NULL,
    email TEXT,
    phone TEXT
)
''')

# 创建订单表
cursor.execute('''
CREATE TABLE IF NOT EXISTS orders (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER,
    service_time TEXT,
    service_location TEXT,
    escort_id INTEGER,
    FOREIGN KEY (user_id) REFERENCES users (id),
    FOREIGN KEY (escort_id) REFERENCES users (id)
)
''')

# 创建评价表
cursor.execute('''
CREATE TABLE IF NOT EXISTS reviews (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    order_id INTEGER,
    attitude_rating INTEGER,
    professional_rating INTEGER,
    comment TEXT,
    FOREIGN KEY (order_id) REFERENCES orders (id)
)
''')

# 创建健康信息表
cursor.execute('''
CREATE TABLE IF NOT EXISTS health_info (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER,
    health_data TEXT,
    FOREIGN KEY (user_id) REFERENCES users (id)
)
''')

# 注册函数
def register():
    username = username_entry.get()
    password = password_entry.get()
    email = email_entry.get()
    phone = phone_entry.get()

    # 检查必填项是否都已填写
    if not all([username, password]):
        messagebox.showerror("错误", "用户名和密码必填")
        return

    # 对密码进行哈希处理
    hashed_password = hashlib.sha256(password.encode()).hexdigest()

    try:
        cursor.execute("INSERT INTO users (username, password, email, phone) VALUES (?,?,?,?)",
                       (username, hashed_password, email, phone))
        conn.commit()
        messagebox.showinfo("成功", "注册成功，请登录")
        root.destroy()
        login()
    except sqlite3.IntegrityError:
        messagebox.showerror("错误", "用户名已存在")

# 登录函数
def login():
    username = username_entry.get()
    password = password_entry.get()

    # 检查必填项是否都已填写
    if not all([username, password]):
        messagebox.showerror("错误", "用户名和密码必填")
        return

    # 对密码进行哈希处理
    hashed_password = hashlib.sha256(password.encode()).hexdigest()

    cursor.execute("SELECT * FROM users WHERE username =? AND password =?", (username, hashed_password))
    user = cursor.fetchone()
    if user:
        messagebox.showinfo("成功", "登录成功")
        root.destroy()
        main_menu(user[0])  # 传入用户 ID
    else:
        messagebox.showerror("错误", "用户名或密码错误")

# 预约服务函数
def book_service(user_id):
    def submit_booking():
        service_time = time_entry.get()
        service_location = location_entry.get()
        escort_username = escort_entry.get()

        # 检查必填项是否都已填写
        if not all([service_time, service_location, escort_username]):
            messagebox.showerror("错误", "服务时间、地点和陪诊人员必填")
            return

        cursor.execute("SELECT id FROM users WHERE username =?", (escort_username,))
        escort_id = cursor.fetchone()
        if escort_id:
            escort_id = escort_id[0]
            cursor.execute("INSERT INTO orders (user_id, service_time, service_location, escort_id) VALUES (?,?,?,?)",
                           (user_id, service_time, service_location, escort_id))
            conn.commit()
            messagebox.showinfo("成功", "预约成功")
            booking_window.destroy()
        else:
            messagebox.showerror("错误", "陪诊人员不存在")

    booking_window = tk.Toplevel()
    booking_window.title("预约陪诊服务")

    tk.Label(booking_window, text="服务时间:").grid(row=0, column=0)
    time_entry = tk.Entry(booking_window)
    time_entry.grid(row=0, column=1)

    tk.Label(booking_window, text="服务地点:").grid(row=1, column=0)
    location_entry = tk.Entry(booking_window)
    location_entry.grid(row=1, column=1)

    tk.Label(booking_window, text="陪诊人员:").grid(row=2, column=0)
    escort_entry = tk.Entry(booking_window)
    escort_entry.grid(row=2, column=1)

    tk.Button(booking_window, text="提交预约", command=submit_booking).grid(row=3, column=0, columnspan=2)

# 查看订单函数
def view_orders(user_id):
    orders_window = tk.Toplevel()
    orders_window.title("我的订单")

    cursor.execute("SELECT * FROM orders WHERE user_id =?", (user_id,))
    orders = cursor.fetchall()

    for i, order in enumerate(orders):
        order_info = f"订单 ID: {order[0]}\n服务时间: {order[2]}\n服务地点: {order[3]}\n陪诊人员 ID: {order[4]}"
        tk.Label(orders_window, text=order_info).grid(row=i, column=0)

# 在线咨询函数（这里只是简单模拟，实际可能需要连接到客服系统）
def online_consultation():
    messagebox.showinfo("咨询", "请联系客服电话：400-123-4567 或发送邮件至 support@hospital.com")

# 服务评价函数
def rate_service(user_id):
    def submit_rating():
        order_id = int(order_id_entry.get())
        attitude_rating = attitude_scale.get()
        professional_rating = professional_scale.get()
        comment = comment_entry.get()

        cursor.execute("INSERT INTO reviews (order_id, attitude_rating, professional_rating, comment) VALUES (?,?,?,?)",
                       (order_id, attitude_rating, professional_rating, comment))
        conn.commit()
        messagebox.showinfo("成功", "评价提交成功")
        rating_window.destroy()

    rating_window = tk.Toplevel()
    rating_window.title("服务评价")

    tk.Label(rating_window, text="订单 ID:").grid(row=0, column=0)
    order_id_entry = tk.Entry(rating_window)
    order_id_entry.grid(row=0, column=1)

    tk.Label(rating_window, text="服务态度评分（1-5）:").grid(row=1, column=0)
    attitude_scale = tk.Scale(rating_window, from_=1, to=5, orient=tk.HORIZONTAL)
    attitude_scale.grid(row=1, column=1)

    tk.Label(rating_window, text="专业水平评分（1-5）:").grid(row=2, column=0)
    professional_scale = tk.Scale(rating_window, from_=1, to=5, orient=tk.HORIZONTAL)
    professional_scale.grid(row=2, column=1)

    tk.Label(rating_window, text="评论:").grid(row=3, column=0)
    comment_entry = tk.Entry(rating_window)
    comment_entry.grid(row=3, column=1)

    tk.Button(rating_window, text="提交评价", command=submit_rating).grid(row=4, column=0, columnspan=2)

# 健康管理函数（这里只是简单示例，实际可能需要更复杂的逻辑）
def health_management(user_id):
    def save_health_info():
        health_data = data_entry.get()
        cursor.execute("INSERT INTO health_info (user_id, health_data) VALUES (?,?)", (user_id, health_data))
        conn.commit()
        messagebox.showinfo("成功", "健康信息保存成功")
        health_window.destroy()

    health_window = tk.Toplevel()
    health_window.title("健康管理")

    tk.Label(health_window, text="请输入健康信息:").grid(row=0, column=0)
    data_entry = tk.Entry(health_window)
    data_entry.grid(row=0, column=1)

    tk.Button(health_window, text="保存信息", command=save_health_info).grid(row=1, column=0, columnspan=2)

# 主菜单函数
def main_menu(user_id):
    main_window = tk.Tk()
    main_window.title("陪诊小程序")

    tk.Button(main_window, text="预约服务", command=lambda: book_service(user_id)).grid(row=0, column=0)
    tk.Button(main_window, text="查看订单", command=lambda: view_orders(user_id)).grid(row=1, column=0)
    tk.Button(main_window, text="在线咨询", command=online_consultation).grid(row=2, column=0)
    tk.Button(main_window, text="服务评价", command=lambda: rate_service(user_id)).grid(row=3, column=0)
    tk.Button(main_window, text="健康管理", command=lambda: health_management(user_id)).grid(row=4, column=0)

    main_window.mainloop()

# 初始登录/注册界面
root = tk.Tk()
root.title("陪诊小程序 - 登录/注册")

tk.Label(root, text="用户名:").grid(row=0, column=0)
username_entry = tk.Entry(root)
username_entry.grid(row=0, column=1)

tk.Label(root, text="密码:").grid(row=1, column=0)
password_entry = tk.Entry(root, show="*")
password_entry.grid(row=1, column=1)

tk.Label(root, text="邮箱:").grid(row=2, column=0)
email_entry = tk.Entry(root)
email_entry.grid(row=2, column=1)

tk.Label(root, text="电话:").grid(row=3, column=0)
phone_entry = tk.Entry(root)
phone_entry.grid(row=3, column=1)

tk.Button(root, text="注册", command=register).grid(row=4, column=0)
tk.Button(root, text="登录", command=login).grid(row=4, column=1)

root.mainloop()

# 关闭数据库连接
conn.close()